<template>
	<view class="field-input field-form-item">
		<u-form-item :label="label" :required="required" :prop="prop">
			<u-upload
				ref="uUpload"
				:action="getActionUrl"
				:file-list="fileList"
				:max-count="maxFileCount"
				:preview-full-image="isImage"
				:auto-upload="true"
				:custom-btn="true"
				:deletable="!getDisabledStatus() && !readOnly"
				width="160"
				height="160"
				:header="getUploadData"
				:formData="getUploadData"
				name="uploadFile"
				@on-success="onSuccess"
				@on-error="onError"
				@on-remove="onRemove"
			>
				<template v-slot:addBtn>
					<view v-if="!isImage && !getDisabledStatus() && !readOnly" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
						<u-icon name="plus" size="24"></u-icon>上传文件
					</view>
					<view v-else-if="!getDisabledStatus() && !readOnly" class="u-list-item u-add-wrap" hover-class="u-add-wrap__hover" hover-stay-time="150"
						width="160" height="160">
						<u-icon name="camera" class="u-add-btn" size="40"></u-icon>
					</view>
				</template>
			</u-upload>
		</u-form-item>
	</view>
</template>

<script>
	import {
		uploadMixin
	} from '@/utils/mixins';
	import request from '@/common/request'
	import { validateWidget } from '@/utils/validate.js';

	export default {
		name: 'onlineCustomUpload',
		props: {
			value: {
				type: String
			},
			label: {
				type: String
			},
			prop: {
				type: String
			},
			widget: {
				type: Object,
				required: true
			},
			required: {
				type: Boolean,
				default: false
			},
			rules: {
				type: Array
			},
			disabled: {
				type: Boolean,
				default: false
			},
			readOnly: {
				type: Boolean,
				default: false
			}
		},
		mixins: [uploadMixin],
		inject: ['form'],
		data() {
			return {
				fileList: [],
				errorMessage: ''
			}
		},
		methods: {
			getDisabledStatus() {
				if (this.widget.eventInfo && this.widget.eventInfo[this.OnlineFormEventType.DISABLE]) {
					return this.widget.eventInfo[this.OnlineFormEventType.DISABLE]();
				} else {
					return this.disabled;
				}
			},
			onValueChange() {
				let value = (this.fileList || []).map(item => {
					return {
						name: item.name,
						filename: item.filename,
						uploadPath: item.uploadPath
					}
				});
				value = JSON.stringify(value);
				this.$emit('input', value, this.widgetConfig);
			},
			onSuccess(data, index, lists, name) {
				let file = lists[index].file;
				if (file) {
					let uploadFile = {
						name: file.name,
						...data.data
					}
					this.fileList.push(uploadFile);
					this.onValueChange();
				}
			},
			onError(res, index, lists, name) {
				console.log(res, index, lists, name);
			},
			onRemove(index, lists, name) {
				this.fileList.splice(index, 1);
				this.onValueChange();
			},
			validateWidget() {
				return new Promise((resolve, reject) => {
					validateWidget(this.rules, this.value).then(res => {
						this.errorMessage = '';
						resolve();
					}).catch(e => {
						this.errorMessage = e;
						resolve(e)
					});
				});
			}
		},
		computed: {
			isImage() {
				let column = this.widget.bindData.column || this.widget.column;
				return column ? (column.fieldKind === this.SysOnlineFieldKind.UPLOAD_IMAGE) : false;
			},
			maxFileCount() {
				return this.widget.column ? this.widget.column.maxFileCount : 0;
			},
			buildFlowParam() {
				let flowParam = {};
				let flowData = this.form().flowData;
				if (flowData) {
					if (flowData.processDefinitionKey) flowParam.processDefinitionKey = flowData.processDefinitionKey;
					if (flowData.processInstanceId) flowParam.processInstanceId = flowData.processInstanceId;
					if (flowData.taskId) flowParam.taskId = flowData.taskId;
				}
				return flowParam;
			},
			getDownloadUrl() {
				if (this.widget.props.downloadUrl == null || this.widget.props.downloadUrl === '') {
					if (this.widget.relation) {
						return '/admin/online/onlineOperation/downloadOneToManyRelation/' + (this.widget.datasource || {})
							.variableName;
					} else {
						return '/admin/online/onlineOperation/downloadDatasource/' + (this.widget.datasource || {})
							.variableName;
					}
				} else {
					return this.widget.props.downloadUrl;
				}
			},
			getActionUrl() {
				if (this.widget.props.actionUrl == null || this.widget.props.actionUrl === '') {
					if (this.widget.relation) {
						return this.getUploadActionUrl('admin/online/onlineOperation/uploadOneToManyRelation/' + (this
							.widget.datasource || {}).variableName);
					} else {
						return this.getUploadActionUrl('admin/online/onlineOperation/uploadDatasource/' + (this.widget
							.datasource || {}).variableName);
					}
				} else {
					return this.getUploadActionUrl(this.widget.props.actionUrl);
				}
			},
			getUploadData() {
				let token = uni.getStorageSync('token')
				let temp = {
					...this.buildFlowParam,
					datasourceId: (this.widget.datasource || {}).datasourceId,
					asImage: this.isImage ? 1 : 0,
					fieldName: (this.widget.column || {}).columnName,
					Authorization: token
				}
				if ((this.widget.relation || {}).relationId) temp.relationId = (this.widget.relation || {}).relationId;
				let flowData = this.form().flowData;
      	if (flowData && flowData.processDefinitionKey) temp.processDefinitionKey = flowData.processDefinitionKey;
				return temp;
			}
		},
		watch: {
			value: {
				handler(newValue) {
					setTimeout(() => {
						this.fileList = [];
						if (this.$refs.uUpload) this.$refs.uUpload.clear();
						if (newValue != null && newValue != '') {
							let downloadParams = {
								...this.buildFlowParam,
								datasourceId: (this.widget.datasource || {}).datasourceId,
								fieldName: this.widget.column.columnName,
								asImage: this.isImage,
								dataId: this.form().getPrimaryData(this.widget) || ''
							}
							if (this.widget.relation) downloadParams.relationId = this.widget.relation.relationId;
							let temp = JSON.parse(newValue);
							temp = Array.isArray(temp) ? temp.map(item => {
								return {
									...item,
									downloadUri: this.getDownloadUrl
								}
							}) : [];
							this.fileList = this.parseUploadData(JSON.stringify(temp), downloadParams);
							console.log(this.fileList);
						}
					}, 30);
				},
				immediate: true
			}
		}
	}
</script>

<style scoped lang="scss">
	.u-list-item {
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgb(244, 245, 246);
		width: 160rpx;
		height: 160rpx;
		margin-left: -6rpx;
	}

	.u-add-wrap {
		flex-direction: column;
		font-size: 26rpx;
	}

	.slot-btn {
		border: 1px solid $u-type-primary;
		padding: 6rpx 14rpx;
		font-size: 28rpx;
		color: $u-type-primary;
		border-radius: 4rpx;
	}
</style>